<?php

namespace app\listing\logic;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\listing\validate\ShopProductEdit;
use app\order\logic\OrderBtLogic;
use app\systems\logic\MqTaskPushLogic;
use app\listing\logic\ShopifyListingLogic;
use think\facade\Db;
class ListingShopLogic extends BasicLogic
{

    /**
     * @desc    获取店铺在线产品列表
     * @author  luckyXiong
     * @date    2024-12-28
     */
    public function getProductList($params=[]){
        $limit                = getIsset($params,'limit',10);
        $shop_id              = getIsset($params,'shop_id');
        $spu                  = getIsset($params,'spu');
        $product_type         = getIsset($params,'product_type');
        $listing_status       = getIsset($params,'listing_status');
        $product_variant_type = getIsset($params,'product_variant_type');
        $product_title        = getIsset($params,'product_title');
        $created_time         = getIsset($params,'create_time');
        $where = [];
        $order = [];

        if($shop_id){
            $where[] = ['shop_id', '=',$shop_id];
        }

        if($listing_status){
            $where[] = ['listing_status', '=',$listing_status];
        }

        if($spu){
            $where[] = ['spu', 'like', '%' . $spu . '%'];
        }

        if (!empty($created_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($created_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($created_time[1]) + 3600*24-1)];
        }

        if($product_type){
            $where[] = ['product_type', '=',$product_type];
        }

        if($product_title){
            $where[] = ['product_title', 'like', '%' . $product_title . '%'];
        }

        if($product_variant_type){
            $where[] = ['product_variant_type', '=',$product_variant_type];
        }

        $order['create_time'] = 'desc';

        $field = '*';
        $res   = Db::name('listing_shop_product')
            ->field($field)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $list = $res->items()?:[];
        $arr = [];

        $product_attr_type = Db::name('product_attr_level')->field('type_id,type_name')->where(['parent_id'=>0])->select()->toArray();
        $type_ids          = array_column($product_attr_type,null,'type_id');
        //批量获取店铺名称;
        $shop_ids       = array_column($list,'shop_id');
        $shop_names     = Db::name('shops')->field('id,name,domain')->whereIn('id',$shop_ids)->select()->toArray();
        $shop_names_map = array_column($shop_names,null,'id');
        //批量获取sku图片;
        $spus  = array_column($list,'spu');
        //批量获取图片地址;
        $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');

        foreach($list as $k=>$v){
            $shopNames                = $shop_names_map[$v['shop_id']]??[];
            $shop_name                = $shopNames['name']??'';
            $domain_name              = $shopNames['domain']??'';
            $product_types            = $type_ids[$v['product_type']]??[];
            $arr[$k]['id']            = $v['id'];
            $product_images_product   = $products_map[$v['spu']]??[];
            $product_images           = $product_images_product['product_images']??[];
            $display_images           = $product_images ? current(json_decode($product_images)) : '';
            $arr[$k]['basic_image']   = $display_images;
            $arr[$k]['spu']           = $v['spu'];
            $arr[$k]['shop_id']       = $v['shop_id'];
            $arr[$k]['product_title'] = $v['product_title'];
            $arr[$k]['product_shopify_id'] = $v['product_shopify_id']??'';
            $arr[$k]['product_variant_type_value'] = $v['product_variant_type']== '1' ? '单品' :'多变体';
            $arr[$k]['product_type_value'] = $product_types['type_name']??'';
            $arr[$k]['shop_name']          = $shop_name;
            $arr[$k]['listing_status']     = $v['listing_status'];
            $arr[$k]['create_time']        = $v['create_time'];
            $arr[$k]['update_time']        = $v['update_time'];
            $arr[$k]['listing_time']         = $v['listing_time'];
            $domain_names                    = 'https://'.$domain_name.'/products/';
            $arr[$k]['product_shopify_url']  = $v['seo_title'] ? $domain_names.$v['seo_title'] : $domain_names.strtolower($v['product_title']);
            $arr[$k]['remark']               = $v['remark'];
            $arr[$k]['remark_color']         = $v['remark_color'];
            $arr[$k]['supply_url']           = $v['supply_url'];
            $arr[$k]['shop_domain_name']     = $domain_names;
        }

        $data = [
            'list'   => $arr,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc    获取sku列表信息
     * @author  luckyXiong
     * @date    2024-11-28
     */
    public function get_sku_list($params=[]){
        $id             = $params['id']??'';
        $shop_id        = $params['shop_id']   ??'';
        $limit          = $params['limit']??10;
        $page           = $params['page'] ??1;
        $field          = 'id,spu,product_variant_type,product_images,variant_json,options';
        $list           = Db::name('listing_shop_product')->field($field)->where(['id'=>$id,'shop_id'=>$shop_id])->find();
        $variant_json   = json_decode($list['variant_json'],true);
        //批量获取图片地址;
        $skus           = array_column($variant_json,'sku');
        $info           = Db::name('product_seller_sku')->field('id,seller_sku,image_info')->whereIn('seller_sku',$skus)->select()->toArray();
        $image_map      = array_column($info,'image_info','seller_sku');
        foreach($variant_json as $k=>$v){
                $image_info              = $image_map[$v['sku']]??'';
                $arr[$k]['id']           = $k+1;
                $arr[$k]['image_url']    = $image_info;
                $arr[$k]['sku']          = $v['sku']??'';
                $arr[$k]['price']        = $v['price']??'';
                $arr[$k]['inventory_quantity']= $v['inventory_quantity']??'0';
                $arr[$k]['weight']       = $v['weight']??'';
                $arr[$k]['shop_id']      = $shop_id;
            }
            $result = paginateArray($arr,$page, $limit);
            $res_list= [
                'list'  => $result['data'],
                'total' => $result['total'],
            ];
        return  $this->jsonMessage(200,true,'获取成功',$res_list);
    }





    /**
     * @desc    获取在线店铺产品详情接口
     * @author  luckyXiong
     * @date    2024-12-29
     */
    public function getInfo($params=[]){
        $id                     = $params['id']??'';
        $info                   = Db::name('listing_shop_product')->where('id',$id)->find();
        $info['product_images'] = $info['product_images'] ? json_decode($info['product_images']):'';
        $info['variant_json']   = $info['variant_json']   ? json_decode($info['variant_json']):'';
        $shop_name              = Db::name('shops')->where(['id'=>$info['shop_id']])->value('name');
        $info['shop_name']      = $shop_name;
        if(isset($info['publish_response'])) unset($info['publish_response']);
        return $this->jsonMessage(200, true,'获取成功', $info);
    }


    /**
     * @desc    编辑店铺信息接口
     * @author  luckyXiong
     * @date    2024-12-28
     */
    public function edit_shop_product($params=[]){
        //验证器参数验证
        $validate    = new ShopProductEdit();
        $res         = $validate->check($params);
        if(!$res)      return  $this->jsonMessage(201, false, $validate->getError(), null);
        $id                   =  $params['id']??'';
        $spu                  =  $params['spu']??'';
        $product_variant_type =  $params['product_variant_type']??'';

        $product_title        =  $params['product_title']??'';
        $product_tags         =  $params['product_tags']??'';
        $product_desc         =  $params['product_desc']??'';


        $seo_title            =  $params['seo_title']??'';
        $seo_desc             =  $params['seo_desc']??'';
        $seo_url              =  isset($params['seo_url']) ? strtolower(str_replace(' ', '-', $params['seo_url'])):'';
        $product_type         =  $params['product_type']??'';
        $supply_url           =  $params['supply_url']??'';
        $product_images       =  $params['product_images']??'';
        $options              =  $params['options']??'';
        $variant_json         =  $params['variant_json']??'';

        if($product_variant_type ==2 && !$variant_json){
            return  $this->jsonMessage(201,false,'产品变种类型不能为空!',null);
        }

        $product_update = [
            'spu'                      => trim($spu),
            'product_tags'             => trim($product_tags),
            'product_title'            => trim($product_title),
            'product_desc'             => trim($product_desc),
            'product_type'             => trim($product_type),
            'supply_url'               => trim($supply_url),
            'seo_title'                => $seo_title,
            'seo_desc'                 => $seo_desc,
            'seo_url'                  => $seo_url,
            'product_images'           => $product_images ? json_encode($product_images):'',
            'options'                  => $options        ? json_encode($options):'',
            'variant_json'             => $variant_json   ? json_encode($variant_json):'',
            'update_time'              => date("Y-m-d H:i:s", time()),
        ];

        try {
            Db::startTrans(); // 开启事务
            Db::name('listing_shop_product')->where('id',$id)->update($product_update);
            Db::commit(); // 提交事务
            return json(DefaultResponse(200, true, '编辑成功', ''));
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            return json(DefaultResponse(200, true, $e->getMessage(), ''));
        }
    }


    /**
     * @desc    添加备注接口
     * @author  luckyXiong
     * @date    2024-12-30
     */
    public function add_remark($params=[]){
         $id           = $params['id']??'';
         $remark       = $params['remark']??'';
         $remark_color = $params['remark_color']??'';
         if(!$id){
             return $this->jsonMessage(201, false,'ID不能为空!', null);
         }
         $product_update = [
              'remark'      =>$remark,
              'remark_color'=>$remark_color,
         ];
         Db::name('listing_shop_product')->where('id',$id)->update($product_update);
         return $this->jsonMessage(200, true,'操作成功', null);
    }


    /**
     * @desc    编辑店铺信息接口
     * @author  luckyXiong
     * @date    2024-12-28
     */
    public function edit_publish_product($params=[]){
        //验证器参数验证
        $id                   =  $params['id']??'';
        $product_variant_type =  $params['product_variant_type']??'';
        $product_title        =  $params['product_title']??'';
        $product_tags         =  $params['product_tags']??'';
        $product_desc         =  $params['product_desc']??'';

        $seo_title            =  $params['seo_title']??'';
        $seo_desc             =  $params['seo_desc']??'';
        if(isset($params['seo_url']) && $params['seo_url']){
            $seo_url  = strtolower(str_replace(' ', '-', $params['seo_url']));
        }else{
            $seo_url  = '';
        }

        $product_type         =  $params['product_type']??'';
        $supply_url           =  $params['supply_url']??'';
        $product_images       =  $params['product_images']??'';
        $options              =  $params['options']??'';
        $variant_json         =  $params['variant_json']??'';

        if($product_variant_type ==2 && !$variant_json){
            return  $this->jsonMessage(201,false,'产品变种类型不能为空!',null);
        }

        $product_update = [
                'product_tags'             => trim($product_tags),
                'product_title'            => trim($product_title),
                'product_desc'             => trim($product_desc),
                'product_type'             => trim($product_type),
                'supply_url'               => trim($supply_url),
                'seo_title'                => $seo_title,
                'seo_desc'                 => $seo_desc,
                'seo_url'                  => $seo_url,
                'product_images'           => $product_images ? json_encode($product_images):'',
                'options'                  => $options        ? json_encode($options):'',
                'variant_json'             => $variant_json   ? json_encode($variant_json):'',
                'update_time'              => date("Y-m-d H:i:s", time()),
        ];
        return  Db::name('listing_shop_product')->where('id',$id)->update($product_update);
    }


    /**
     * @desc    产品发布
     * @author  luckyXiong
     * @date    2024-12-02
     */
    public function send_product($params=[]){
        $id = $params['id']??'';
        if(!$id){
            return $this->jsonMessage(201, false,'ID不能为空!', null);
        }

        $info = Db::name('listing_shop_product')->where('id',$id)->find();
        //刊登数据组装
        $list = self::get_send_data($info);
        //推动数据到队列;
        MqTaskPushLogic::mq_task_push(
            '',
            MqQueueName::QUEUE_PRODUCT_SEND_UP_UNDER,
            [
                'listing_shop_product_id'=>$id,
                'product_id'             =>$info['product_shopify_id'],
                'shop_id'                =>$info['shop_id'],
                'send_data'              =>$list,
            ],
            false
        );
        //更新刊登状态为6
        Db::name('listing_shop_product')->where(['id'=>$id])->update(
            [
                'listing_status'    =>6
            ]
        );
        //直接触发MQ消费 2024-11-30
        (new OrderBtLogic())->getCrontab();
        return $this->jsonMessage(200, true,'操作成功', null);
    }


    /**
     * @desc    编辑产品发布
     * @author  luckyXiong
     * @date    2024-12-01
     */
    public function update_send_product($params=[]){
        $id = $params['id']??'';
        if(!$id){
            return $this->jsonMessage(201, false,'ID不能为空!', null);
        }
        $res = self::edit_publish_product($params);
        if($res){
            //调用编辑shopify接口
            $info = Db::name('listing_shop_product')->where('id',$id)->find();
            //刊登数据组装
            $list = self::get_send_data($info);
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_PRODUCT_SEND_UP_UNDER,
                [
                    'listing_shop_product_id'=>$id,
                    'product_id'             =>$info['product_shopify_id'],
                    'shop_id'                =>$info['shop_id'],
                    'send_data'              =>$list,
                ],
                false
            );
            //更新刊登状态为2 在线
            Db::name('listing_shop_product')->where(['id'=>$id])->update(['listing_status'=>2]);
        }
        //直接触发MQ消费 2024-12-03
        (new OrderBtLogic())->getCrontab();
        return $this->jsonMessage(200, true,'操作成功', null);
    }



    /**
     * @desc    刊登数据组装
     * @author  luckyXiong
     * @date    2024-12-02
     */
    private function get_send_data($info=[]){
        //获取店铺信息;
        $shop_info         = Db::name('shops')->field('id,name,myshopify_domain,app_secret')->where(['id'=>$info['shop_id']])->find();
        $product_attr_type = Db::name('product_attr_level')->where(['parent_id'=>0,'type_id'=>$info['product_type']])->value('type_name');
        if($product_attr_type){
            $product_attr_type = preg_replace('/[^a-zA-Z]/', '', $product_attr_type);
        }

        $variant_json  = json_decode($info['variant_json'],true);

        foreach($variant_json as $k=>$v) {
            if (isset($v['option2']) && $v['option2']) {
                $variant_json[$k]['option2'] = $v['option2'];
            }
            if (isset($v['option3']) && $v['option3']) {
                $variant_json[$k]['option3'] = $v['option3'];
            }


            if (isset($v['inventory_support']) && $v['inventory_support']) {
                switch ($v['inventory_support']) {
                    case 1:
                        $variant_json[$k]['inventory_management'] = 'shopify';
                        $variant_json[$k]['inventory_policy'] = 'continue';
                        break;
                    case 2:
                        $variant_json[$k]['inventory_management'] = 'shopify';
                        $variant_json[$k]['inventory_policy'] = 'deny';
                        break;
                    case 3:
                        $variant_json[$k]['inventory_management'] = null;
                        $variant_json[$k]['inventory_policy'] = 'deny';
                        break;
                }
            } else {
                $variant_json[$k]['inventory_management'] = 'shopify';
                $variant_json[$k]['inventory_policy'] = 'continue';
            }

            $variant_json[$k]['weight_unit'] = 'kg';
            $variant_json[$k]['fulfillment_service'] = 'manual';  //手动履行，表示需要商家手动处理发货。
            $variant_json[$k]['taxable'] = 'false';  //否需要征收销售税
            if (isset($v['inventory_support'])) unset($variant_json[$k]['inventory_support']);
        }
        $send_arr = [
            'title'           => $info['product_title'] ?? '',
            'body_html'       => $info['product_desc'] ?? '',
            'vendor'          => isset($info['supply_shop_name']) && $info['supply_shop_name']  ? $shop_info['supply_shop_name'] : $shop_info['name'],
            'product_type'    => $product_attr_type,
            'published_scope' => $info['web'] ?? '',
            'handle'          => $info['seo_url'] ?? '',
            'tags'            => $info['product_tags'] ?? '',
            'status'          => 'active',
            'images'          => $info['product_images'] ? json_decode($info['product_images'], true) : '',
            'options'         => $info['options']? json_decode($info['options'],true) :'',
            'variants'        => $variant_json,
        ];
        return [
            'product' => $send_arr
        ];
    }



    /**
     * @desc    下架产品
     * @author  luckyXiong
     * @date    2024-12-01
     */
    public function under_product($params=[]){
        $id      = $params['id']??'';
        $shop_id = $params['shop_id']??'';
        if(!$id){
            return $this->jsonMessage(201, false,'ID不能为空!', null);
        }
        //  status : active 活跃  archived 下架
        $shop_info     = Db::name('shops')->where('id', $shop_id)->find();
        $product_id    = Db::name('listing_shop_product')->where('id',$id)->value('product_shopify_id');
        $version       = Config('Logisticskey.shopify.api_versoin');
        $fulfill_url   = $shop_info['myshopify_domain'].$version.'/products/'.$product_id.'.json';
        $token         = $shop_info['app_secret'];
        $send_data     = [
                 'product'=>[
                     'id'     =>$product_id,
                     'status' =>'archived',
                 ]
        ];
        $return  = HttpUtil::putUrlShopify($fulfill_url, $send_data, $token);
        if(isset($return['product']['id']) && $return['product']['id']){
            Db::name('listing_shop_product')->where(['id'=>$id])->update(
                [
                    'listing_status'    =>3,
                    'update_time'       =>date("Y-m-d H:i:s", time()),
                ]
            );
        }
        return   $this->jsonMessage(200, true,'操作成功', null);
    }


    /**
     * @desc    上架产品
     * @author  luckyXiong
     * @date    2024-12-01
     */
    public function list_product($params=[]){
        $id      = $params['id']??'';
        $shop_id = $params['shop_id']??'';
        if(!$id){
            return $this->jsonMessage(201, false,'ID不能为空!', null);
        }
        //  status : active 活跃  archived 下架
        $shop_info     = Db::name('shops')->where('id', $shop_id)->find();
        $product_id    = Db::name('listing_shop_product')->where('id',$id)->value('product_shopify_id');
        $version       = Config('Logisticskey.shopify.api_versoin');
        $fulfill_url   = $shop_info['myshopify_domain'].$version.'/products/'.$product_id.'.json';
        $token         = $shop_info['app_secret'];
        $send_data     = [
            'product'=>[
                'id'     =>$product_id,
                'status' =>'active',
            ]
        ];
        $return  = HttpUtil::putUrlShopify($fulfill_url, $send_data, $token);
        if(isset($return['product']['id']) && $return['product']['id']){
            Db::name('listing_shop_product')->where(['id'=>$id])->update(
                [
                    'listing_status'    =>2,
                    'update_time'       =>date("Y-m-d H:i:s", time()),
                ]
            );
        }
        return   $this->jsonMessage(200, true,'操作成功', null);
    }


    /**
     * @desc    删除产品
     * @author  luckyXiong
     * @date    2024-12-01
     */
    public function delete_product($params=[]){
        $id      = $params['id']??'';
        if(!$id){
            return $this->jsonMessage(201, false,'ID不能为空!', null);
        }
        Db::name('listing_shop_product')->where('id',$id)->delete();
        return $this->jsonMessage(200, true,'操作成功', null);
    }



}